<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=h1, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
      body {
        margin: 0;
        padding: 30px;
      }
      a {
        text-decoration: none;
        margin-bottom: 20px;
      }
      table,
      th,
      td {
        border: 1px solid black;
        /* 边线重合 */
        border-spacing: 0;
        border-collapse: collapse;
        text-align: center;
      }
      th,
      rd {
        padding: 5px 10px;
      }
    </style>
  </head>
  <body>
    <h3>用户列表</h3>
    <a href="./add.html">添加用户</a>
    <table>
      <thead>
        <tr>
          <th>id</th>
          <th>用户名</th>
          <th>密码</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody></tbody>
    </table>

    <script>
      //获取tobdy对象
      const tbody = document.querySelector("tbody")

      // 发送axios请求
      axios
        .get("http://localhost:3000/users")
        .then((res) => {
          //获取所有的用户数组
          var arr = res.data

          //将用户数组中的js转成tr的一个DOM字符串，再拼接成一整个字符串，填充到tbody中
          tbody.innerHTML = arr.map(item=> {
            return `<tr>
                      <td>${item.id}</td>
                      <td>${item.username}</td>
                        <td>${item.password}</td>
                    <td>
                        <a href="./eidt.html?id=${item.id}">编辑</a>
                        <a href="" onclick='deleteItem(${item.id})'>删除</a>
                    </td>
                </tr>`
          }).join('')
        })
        

        //实现删除方法
        function deleteItem(id){
          const flag = confirm('你确定要删除吗')
          if(flag){
            axios.delete(`http://localhost:3000/users/${id}`).then(res=>{
              location.href = './index.html'
            })
          }
        }
    </script>
  </body>
</html>
